/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.app.course.study.web;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.mapper.JsonMapper;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.app.course.study.entity.TcourseStudy;
import com.jeesite.modules.app.course.study.service.TcourseStudyService;
import com.jeesite.modules.conf.AppController;
import com.jeesite.modules.conf.MessageCode;
import com.jeesite.modules.zx.course.authorization.entity.TcourseAuthorization;
import com.jeesite.modules.zx.course.authorization.service.TcourseAuthorizationService;
import com.jeesite.modules.zx.course.entity.Tcourses;
import com.jeesite.modules.zx.course.service.TcoursesService;

/**
 * 课程学习表Controller
 * @author zpp
 * @version 2020-01-26
 */
@Controller
@RequestMapping(value = "/app/course/study/tcourseStudy/")
public class TcourseStudyController{

	@Autowired
	private TcourseStudyService tcourseStudyService;
	@Autowired
	private TcourseAuthorizationService tcourseAuthorizationService;
	@Autowired
	private TcoursesService tcoursesService;
	/**
	 * 查询列表
	 */
	@RequiresPermissions("app:course:study:tcourseStudy:view")
	@RequestMapping(value = {"list", ""})
	public String list(TcourseStudy tcourseStudy, Model model) {
		model.addAttribute("tcourseStudy", tcourseStudy);
		return "modules/app/course/study/tcourseStudyList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("app:course:study:tcourseStudy:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<TcourseStudy> listData(TcourseStudy tcourseStudy, HttpServletRequest request, HttpServletResponse response) {
		tcourseStudy.setPage(new Page<>(request, response));
		Page<TcourseStudy> page = tcourseStudyService.findPage(tcourseStudy);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("app:course:study:tcourseStudy:view")
	@RequestMapping(value = "form")
	public String form(TcourseStudy tcourseStudy, Model model) {
		model.addAttribute("tcourseStudy", tcourseStudy);
		return "modules/app/course/study/tcourseStudyForm";
	}

	/**
	 * 保存课程学习表
	 */
	@RequiresPermissions("app:course:study:tcourseStudy:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated TcourseStudy tcourseStudy) {
		tcourseStudyService.save(tcourseStudy);
		return "保存课程学习表成功！";
	}
	
	/**
	 * 停用课程学习表
	 */
	@RequiresPermissions("app:course:study:tcourseStudy:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(TcourseStudy tcourseStudy) {
		tcourseStudy.setStatus(TcourseStudy.STATUS_DISABLE);
		tcourseStudyService.updateStatus(tcourseStudy);
		return "停用课程学习表成功";
	}
	
	/**
	 * 启用课程学习表
	 */
	@RequiresPermissions("app:course:study:tcourseStudy:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(TcourseStudy tcourseStudy) {
		tcourseStudy.setStatus(TcourseStudy.STATUS_NORMAL);
		tcourseStudyService.updateStatus(tcourseStudy);
		return "启用课程学习表成功";
	}
	
	/**
	 * 删除课程学习表
	 */
	@RequiresPermissions("app:course:study:tcourseStudy:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(TcourseStudy tcourseStudy) {
		tcourseStudyService.delete(tcourseStudy);
		return "删除课程学习表成功！";
	}
	@RequestMapping(value = "selectCourseStudy")
	public void selectCourseStudy(HttpServletRequest request,HttpServletResponse response){
		String userCode=request.getParameter("userId");
		if(StringUtils.isBlank(userCode)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED,"用户信息未发现");
			return;
		}
		TcourseAuthorization authorCourse=new TcourseAuthorization();
		authorCourse.setUserId(userCode);
		List<TcourseAuthorization> findList = tcourseAuthorizationService.findList(authorCourse);
		List<String> list=new ArrayList<String>();
		for(TcourseAuthorization auth:findList){
			String courseId = auth.getCourseId();
			list.add(courseId);
		}
		if(list.size()>0){
			Tcourses course=new Tcourses();
			course.setPage(new Page<>(request, response));
			course.setParentCode("0");
			course.getSqlMap().getWhere().and("id", QueryType.IN, list);
			try {
				
				Page<Tcourses> findPage = tcoursesService.findPage(course);
				JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(findPage));
				AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);
			} catch (Exception e) {
				AppController.renderErrorString(response, MessageCode.SYSTEM_DB_ERROR, "");
				return;
			}
		}else{
			Page<Tcourses> findPage =new Page<>(request, response);
			JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(findPage));
			AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);
		}
	}
	//selectCoursExercise
	@RequestMapping(value = "selectCoursExercise")
	public void selectCoursExercise(HttpServletRequest request,HttpServletResponse response){
		String userCode=request.getParameter("userId");
		if(StringUtils.isBlank(userCode)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED,"用户信息未发现");
			return;
		}
		TcourseAuthorization authorCourse=new TcourseAuthorization();
		authorCourse.setUserId(userCode);
		List<TcourseAuthorization> findList = tcourseAuthorizationService.findList(authorCourse);
		List<String> list=new ArrayList<String>();
		for(TcourseAuthorization auth:findList){
			String courseId = auth.getCourseId();
			list.add(courseId);
		}
		if(list.size()>0){
			Tcourses course=new Tcourses();
			course.setPage(new Page<>(request, response));
			course.setParentCode("0");
			course.getSqlMap().getWhere().and("id", QueryType.IN, list);
			try {
				
				Page<Tcourses> findPage = tcoursesService.findPage(course);
				JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(findPage));
				AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);
			} catch (Exception e) {
				AppController.renderErrorString(response, MessageCode.SYSTEM_DB_ERROR, "");
				return;
			}
		}else{
			Page<Tcourses> findPage =new Page<>(request, response);
			JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(findPage));
			AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);
		}
	}
	@RequestMapping(value = "coursExerciseList")
	public void coursExerciseList(HttpServletRequest request,HttpServletResponse response){
		String id=request.getParameter("id");
		if(StringUtils.isBlank(id)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "查询标识");
			return;
		}
		Tcourses tcourses=new Tcourses();
		tcourses.setParentCode(id);
		tcourses.setCourseExplain(1);
		List<Tcourses> findList = tcoursesService.findList(tcourses);
		String userId=request.getParameter("userId");
		for(Tcourses tcor:findList){
			TcourseStudy study=new TcourseStudy();
			study.setCourseId(id);
			String courHourId=tcor.getId();
			study.setCourseHourseId(courHourId);
			study.setUserId(userId);
			List<TcourseStudy> findList2 = tcourseStudyService.findList(study);
			for(TcourseStudy ts:findList2){
				String difference = ts.getDifference();
				if(StringUtils.isNotBlank(difference)){
					tcor.setDifference(difference);
				}
			}
		}
		
		JSONArray parseObject = JSONObject.parseArray(JsonMapper.toJson(findList));
		AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);
	}
	@RequestMapping(value = "findPage")
	public void findPage(TcourseStudy entity,HttpServletRequest request,HttpServletResponse response){
		String userId = entity.getUserId();
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED,"用户信息未发现");
			return;
		}
		Page<TcourseStudy> findPage = tcourseStudyService.findPage(entity);
		JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(findPage));
		AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);
	}
	/**
	 * 开始学习课程
	 * @param entity
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "startStudy")
	public void startStudy(TcourseStudy entity,HttpServletRequest request,HttpServletResponse response){
		String courseId = entity.getCourseId();
		if(StringUtils.isBlank(courseId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "课程标识");
			return;
		}
		String courseHourseId = entity.getCourseHourseId();
		if(StringUtils.isBlank(courseHourseId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "课时标识");
			return;
		}
		String userId = entity.getUserId();
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			return;
		}
		List<TcourseStudy> findList = tcourseStudyService.findList(entity);
		if(findList!=null&&findList.size()>0){
			entity=findList.get(0);
		}else{
		    tcourseStudyService.save(entity);
		}
		JSONObject json=JSONObject.parseObject(JsonMapper.toJson(entity));
		AppController.renderSuccessObject(response, json, MessageCode.SUCCESS_ACK);
	}
	/**
	 * 课程播放
	 * @param entity
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "playCourse")
	public void playCourse(TcourseStudy entity,HttpServletRequest request,HttpServletResponse response){
		String id = entity.getId();
		if(StringUtils.isBlank(id)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "操作标识");
			return;
		}
		entity.setPlayDate(LocalDateTime.now());
		tcourseStudyService.update(entity);
		JSONObject json=JSONObject.parseObject(JsonMapper.toJson(entity));
		AppController.renderSuccessObject(response, json, MessageCode.SUCCESS_ACK);
	}
	/**
	 * 课程暂停
	 * @param entity
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "pauseCourse")
	public void pauseCourse(TcourseStudy entity,HttpServletRequest request,HttpServletResponse response){
		String id = entity.getId();
		if(StringUtils.isBlank(id)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "操作标识");
			return;
		}
		TcourseStudy tcourseStudy = tcourseStudyService.get(id);
		LocalDateTime playDate = tcourseStudy.getPlayDate();
		LocalDateTime curr=LocalDateTime.now();
		Duration between = Duration.between(playDate, curr);
		Long millis = between.toMillis();
		
		BigDecimal duration = tcourseStudy.getDuration();
		if(duration==null){
			duration=new BigDecimal(0);
		}
		duration=duration.add(new BigDecimal(millis.doubleValue()));
		
		entity.setPauseDate(curr);
		entity.setDuration(duration);
		tcourseStudyService.update(entity);
		JSONObject json=JSONObject.parseObject(JsonMapper.toJson(entity));
		AppController.renderSuccessObject(response, json, MessageCode.SUCCESS_ACK);
	}
	/**
	 * 课程播放完
	 * @param entity
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "endedCourse")
	public void endedCourse(TcourseStudy entity,HttpServletRequest request,HttpServletResponse response){
		String id = entity.getId();
		if(StringUtils.isBlank(id)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "操作标识");
			return;
		}
		BigDecimal durationCourse=entity.getDuration();
		if(durationCourse==null){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "及时参数");
			return;
		}
		durationCourse=durationCourse.multiply(new BigDecimal(1000));
		TcourseStudy tcourseStudy = tcourseStudyService.get(id);
		LocalDateTime playDate = tcourseStudy.getPlayDate();
		LocalDateTime curr=LocalDateTime.now();
		Duration between = Duration.between(playDate, curr);
		Long millis = between.toMillis();
		
		BigDecimal duration = tcourseStudy.getDuration();
		if(duration==null){
			duration=new BigDecimal(0);
		}
		duration=duration.add(new BigDecimal(millis.doubleValue()));
		if(duration.compareTo(durationCourse)>-1){
			entity.setDifference("ok");
		}		
		entity.setPauseDate(curr);
		entity.setDuration(duration);
		entity.setFinish(1);
		tcourseStudyService.update(entity);
		JSONObject json=JSONObject.parseObject(JsonMapper.toJson(entity));
		AppController.renderSuccessObject(response, json, MessageCode.SUCCESS_ACK);
	}
	
}